package ru.spbsu.neural;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class Utils {

	public static List<TrainingPair<Integer>> scanTrainingFolder(String folderName,
			List<Integer> outputs, Digitizer<Integer> digitizer) {
		List<TrainingPair<Integer>> trainingPairs = new ArrayList<>();

		File folder = new File(folderName);
		for (File file : folder.listFiles()) {
			if (file.isFile() && !file.getName().equals("Thumbs.db")) {
				TrainingPair<Integer> pair = new TrainingPair<Integer>(digitizer.digitize(file),
						outputs);
				trainingPairs.add(pair);
			}
		}

		return trainingPairs;
	}

	/**
	 * 
	 * @param resultFilename
	 * @param trainingPairs
	 */
	public static void createTrainingFile(String resultFilename,
			List<TrainingPair<Integer>> trainingPairs) {
		if (trainingPairs == null || trainingPairs.isEmpty()) {
			System.out.println("No training pairs!");
			return;
		}

		Integer inputsQnt = trainingPairs.get(0).getInput().size();
		Integer outputsQnt = 1;

		File file = new File(resultFilename);
		if (file.exists()) {
			file.delete();
		}
		PrintWriter printWriter = null;
		try {
			printWriter = new PrintWriter(file);

			printWriter.print(trainingPairs.size() + " ");
			printWriter.print(inputsQnt + " ");
			printWriter.println(outputsQnt);

			for (TrainingPair<Integer> pair : trainingPairs) {
				for (Integer i : pair.getInput()) {
					printWriter.print(i.toString() + " ");
				}
				printWriter.println();
				printWriter.println(pair.getOutput().get(0));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			printWriter.close();
		}
	}

	public static float[] integersToFloats(List<Integer> input) {
		float[] result = new float[input.size()];

		for (int i = 0; i < input.size(); i++) {
			result[i] = input.get(i);
		}

		return result;
	}
}
